<template>
  <!-- 自定义导航栏 -->
  <view class="custom-nav">
    <view class="back-btn" @click="goBackHome">
		<image src="/static/img/xiangzuojiantou.png" mode="" style="width: 25px;height: 25px;"></image>
    </view>
    <view class="nav-title">发布房源</view>
  </view>

  <!-- 页面内容 -->
  <view class="content">
    <!-- 房屋信息区域 -->
    <view class="section">
      <text class="section-title">房屋信息</text>

      <!-- 小区名称：用原生 picker 替代 uv-picker -->
      <picker 
        mode="selector" 
        :range="communityColumns[0]" 
        @change="handleCommunityChange"
        class="picker-wrap"
      >
        <view class="info-item">
          <text class="info-label">小区名称</text>
          <view class="info-value">
            <text>{{ communityName || '请选择小区' }}</text>
            <text class="arrow">》</text>
          </view>
        </view>
      </picker>

      <!-- 每月租金 -->
      <view class="info-item">
        <text class="info-label">每月租金</text>
        <view class="info-value">
          <input type="number" v-model="rent" placeholder="请输入租金" class="input">
          <text class="unit"> ¥/月</text>
        </view>
      </view>

      <!-- 建筑面积 -->
      <view class="info-item">
        <text class="info-label">建筑面积</text>
        <view class="info-value">
          <input type="number" v-model="area" placeholder="请输入面积" class="input">
          <text class="unit"> ㎡</text>
        </view>
      </view>

      <!-- 户型：原生 picker -->
      <picker 
        mode="selector" 
        :range="houseTypeColumns[0]" 
        @change="handleHouseTypeChange"
        class="picker-wrap"
      >
        <view class="info-item">
          <text class="info-label">户 型</text>
          <view class="info-value">
            <text>{{ houseType || '请选择户型' }}</text>
            <text class="arrow">》</text>
          </view>
        </view>
      </picker>

      <!-- 所在楼层：原生 picker -->
      <picker 
        mode="selector" 
        :range="floorColumns[0]" 
        @change="handleFloorChange"
        class="picker-wrap"
      >
        <view class="info-item">
          <text class="info-label">所在楼层</text>
          <view class="info-value">
            <text>{{ floor || '请选择楼层' }}</text>
            <text class="arrow">》</text>
          </view>
        </view>
      </picker>

      <!-- 朝向：原生 picker -->
      <picker 
        mode="selector" 
        :range="directionColumns[0]" 
        @change="handleDirectionChange"
        class="picker-wrap"
      >
        <view class="info-item">
          <text class="info-label">朝 向</text>
          <view class="info-value">
            <text>{{ direction || '请选择朝向' }}</text>
            <text class="arrow">》</text>
          </view>
        </view>
      </picker>
    </view>

    <!-- 房屋标题 -->
    <view class="section">
      <text class="section-title">房屋标题</text>
      <input v-model="title" placeholder="请输入房屋标题（如：XX小区精装两室出租）" class="title-input">
    </view>

    <!-- 房屋图像 -->
    <view class="section">
      <text class="section-title">房屋图像</text>
      <view class="image-container">
        <!-- 已上传图片 -->
        <view class="image-item" v-for="(img, index) in images" :key="index">
          <image :src="img" mode="aspectFill"></image>
          <view class="delete-img" @click.stop="deleteImage(index)">×</view>
        </view>

        <!-- 上传按钮 -->
        <view class="upload-btn" @click="chooseImage" v-if="images.length < 5">
          <text class="plus">+</text>
        </view>
      </view>
      <text class="image-tip">最多上传5张图片</text>
    </view>

    <!-- 房屋配置 -->
    <view class="section">
      <text class="section-title">房屋配置</text>
      <view class="facility-grid">
        <view class="facility-item" v-for="(item, index) in facilities" :key="index"
          @click="toggleFacility(index)">
          <view class="facility-icon" :class="{ selected: item.checked }">
            <uv-icon :name="item.icon" color="#2979ff" size="28"></uv-icon>
          </view>
          <text class="facility-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="btn-group">
      <button class="cancel-btn" @click="resetForm">取消</button>
      <button class="submit-btn" @click="submitForm">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

// 表单数据
const communityName = ref('龙江碧桂园华府')
const rent = ref('4500')
const area = ref('60')
const houseType = ref('二室')
const floor = ref('低楼层')
const direction = ref('南')
const title = ref('龙江碧桂园公寓整租')
const images = ref(['/static/news/1.png'])

// 选择器数据（保持不变）
const communityColumns = [['龙江碧桂园华府', '滨江壹号', '城市花园', '阳光小区', '翰林苑']]
const houseTypeColumns = [['一室', '二室', '三室', '四室及以上']]
const floorColumns = [['低楼层', '中楼层', '高楼层']]
const directionColumns = [['东', '南', '西', '北', '东南', '西南', '东北', '西北']]

// 原生 picker change 事件处理
const handleCommunityChange = (e) => {
  communityName.value = communityColumns[0][e.detail.value]
}
const handleHouseTypeChange = (e) => {
  houseType.value = houseTypeColumns[0][e.detail.value]
}
const handleFloorChange = (e) => {
  floor.value = floorColumns[0][e.detail.value]
}
const handleDirectionChange = (e) => {
  direction.value = directionColumns[0][e.detail.value]
}

// 房屋配置
const facilities = ref([{
    name: '衣柜',
    icon: 'red-packet',
    checked: true
  },
  {
    name: '洗衣机',
    icon: 'shopping-cart-fill',
    checked: true
  },
  {
    name: '空调',
    icon: 'lock-opened-fill',
    checked: true
  },
  {
    name: '天然气',
    icon: 'car-fill',
    checked: true
  },
  {
    name: '冰箱',
    icon: 'star-fill',
    checked: true
  },
  {
    name: '热水器',
    icon: 'plus-circle-fill',
    checked: false
  },
  {
    name: '电视',
    icon: 'server-fill',
    checked: false
  },
  {
    name: '淋浴',
    icon: 'eye-fill',
    checked: false
  },
  {
    name: 'WiFi',
    icon: 'empty-wifi-off',
    checked: false
  },
  {
    name: '沙发',
    icon: 'calendar',
    checked: false
  }
])

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 5 - images.value.length,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      images.value = [...images.value, ...res.tempFilePaths]
    }
  })
}

// 删除图片
const deleteImage = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        images.value.splice(index, 1)
      }
    }
  })
}

// 切换配置选择
const toggleFacility = (index) => {
  facilities.value[index].checked = !facilities.value[index].checked
}

// 提交表单
const submitForm = () => {
  if (!communityName.value) return uni.showToast({ title: '请选择小区', icon: 'none' })
  if (!rent.value) return uni.showToast({ title: '请输入租金', icon: 'none' })
  if (!area.value) return uni.showToast({ title: '请输入面积', icon: 'none' })
  if (!title.value) return uni.showToast({ title: '请输入房屋标题', icon: 'none' })
  if (images.value.length === 0) return uni.showToast({ title: '请上传房屋图片', icon: 'none' })

  const formData = {
    communityName: communityName.value,
    rent: rent.value,
    area: area.value,
    houseType: houseType.value,
    floor: floor.value,
    direction: direction.value,
    title: title.value,
    images: images.value,
    facilities: facilities.value.filter(item => item.checked).map(item => item.name)
  }

  // 显示加载提示
  uni.showLoading({ title: '发布中...' })

  // 调用API保存房源数据
      uni.request({
        url: 'http://localhost:8080/houses', // 假设的房源保存接口
        method: 'POST',
        data: formData,
        success: (res) => {
          console.log('提交数据:', formData)
          console.log('保存成功:', res)
          
          // 生成临时ID并保存到本地存储，确保能立即看到数据
          const newHouse = {
            ...formData,
            id: Date.now().toString(), // 生成临时ID
            createdTime: new Date().toISOString()
          };
          
          // 从本地存储获取现有房源列表
          const existingHouses = uni.getStorageSync('localHouses') || [];
          // 添加新房源到列表开头
          existingHouses.unshift(newHouse);
          // 保存回本地存储
          uni.setStorageSync('localHouses', existingHouses);
          
          uni.showToast({ title: '发布成功', icon: 'success' })
          
          // 发布成功后通知发布列表页面刷新数据
          setTimeout(() => {
            uni.navigateTo({
              url: '/ulit/publish/publish',
              success: () => {
                // 通知发布列表页面刷新数据
                uni.$emit('refreshHouses');
              }
            })
          }, 1500)
        },
        fail: (err) => {
          console.error('保存失败:', err)
          
          // 即使API失败，也保存到本地作为临时数据
          const newHouse = {
            ...formData,
            id: Date.now().toString(), // 生成临时ID
            createdTime: new Date().toISOString(),
            isLocalOnly: true // 标记为仅本地数据
          };
          
          // 从本地存储获取现有房源列表
          const existingHouses = uni.getStorageSync('localHouses') || [];
          existingHouses.unshift(newHouse);
          uni.setStorageSync('localHouses', existingHouses);
          
          uni.showToast({ title: '已保存到本地，稍后同步', icon: 'none' })
          
          // 仍然跳转到发布列表页
          setTimeout(() => {
            uni.navigateTo({
              url: '/ulit/publish/publish',
              success: () => {
                uni.$emit('refreshHouses');
              }
            })
          }, 1500)
        },
        complete: () => {
          uni.hideLoading()
        }
      })
}

// 重置表单
const resetForm = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空所有内容吗？',
    success: (res) => {
      if (res.confirm) {
        communityName.value = ''
        rent.value = ''
        area.value = ''
        houseType.value = ''
        floor.value = ''
        direction.value = ''
        title.value = ''
        images.value = []
        facilities.value.forEach(item => item.checked = false)
      }
    }
  })
}

// 返回首页
const goBackHome = () => {
  uni.switchTab({ url: '/pages/index/index', fail: (err) => console.log('返回失败:', err) })
}
</script>

<style scoped>
/* 导航栏样式 */
.custom-nav {
  position: fixed;
  top: var(--status-bar-height, 20px);
  left: 0;
  right: 0;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-sizing: border-box;
  z-index: 999;
}

.back-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.back-icon {
  font-size: 20px;
  color: #0d9b88;
}

.nav-title {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  font-weight: 600;
  color: #0d9b88;
}

/* 内容区样式 */
.content {
  padding: 0px;
  padding-top: calc(var(--status-bar-height, 20px) + 44px + 16px);
  background-color: #f5f4f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 分区样式 */
.section {
  margin-bottom: 24px;
}

.section-title {
  color: #0d9b88;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  display: block;
  padding-left: 4px;
}

/* 原生 picker 包裹层：确保点击区域完整 */
.picker-wrap {
  width: 100%;
}

/* 信息项样式 */
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px;
  background-color: #fff;
  margin-bottom: 1px;
  width: 100%;
  box-sizing: border-box;
  pointer-events: auto;
  cursor: pointer;
}

.info-label {
  color: #666;
  font-size: 15px;
  width: 100px;
}

.info-value {
  flex: 1;
  text-align: right;
  font-size: 15px;
  color: #333;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.arrow {
  color: #ccc;
  margin-left: 8px;
  font-size: 16px;
}

.unit {
  color: #666;
  margin-left: 4px;
}

/* 输入框样式 */
.input {
  text-align: right;
  font-size: 15px;
  color: #333;
  width: 120px;
  padding: 4px 0;
}

.title-input {
  width: 100%;
  padding-left: 10px;
  background-color: #fff;
  border-radius: 4px;
  height: 50px;
  font-size: 15px;
  box-sizing: border-box;
}

/* 图片区域 */
.image-container {
  display: flex;
  gap: 12px;
  margin-top: 12px;
  flex-wrap: wrap;
  padding-left: 10px;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  background-color: #f9f9f9;
  position: relative;
}

.image-item image {
  width: 100%;
  height: 100%;
}

.delete-img {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.upload-btn {
  width: 120px;
  height: 120px;
  border: 1px dashed #0d9b88;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.plus {
  font-size: 24px;
  color: #0d9b88;
}

.image-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  display: block;
}

/* 房屋配置 */
.facility-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 12px;
}

.facility-item {
  width: calc(20% - 12.8px);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.facility-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  color: #0d9b88;
}

.facility-icon.selected {
  background-color: #b2f0f5;
}

/* 底部按钮组 */
.btn-group {
  padding: 20px 16px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 16px;
}

.cancel-btn {
  flex: 1;
  height: 44px;
  border: 1px solid #0d9b88;
  background-color: #fff;
  color: #0d9b88;
  border-radius: 22px;
  font-size: 16px;
  line-height: 44px;
  padding: 0;
}

.submit-btn {
  flex: 1;
  height: 44px;
  background-color: #0d9b88;
  color: #fff;
  border-radius: 22px;
  font-size: 16px;
  line-height: 44px;
  padding: 0;
}

/* 调整内容区域底部边距，避免被按钮组遮挡 */
.content {
  padding-bottom: 80px;
}
</style>